package com.sgolub.commanndsonline.web;
    
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.sgolub.commanndsonline.domain.entity.AdvertisingRegistry;
import com.sgolub.commanndsonline.domain.entity.OperationItem;
import com.sgolub.commanndsonline.domain.entity.UserBasket;
import com.sgolub.commanndsonline.domain.entity.UserOrder;
import com.sgolub.commanndsonline.domain.entity.UserOrderDetail;
import com.sgolub.commanndsonline.domain.proxy.ProxyAdvertisingRegistry;
import com.sgolub.commanndsonline.domain.proxy.ProxyUserBasketTotal;
import com.sgolub.commanndsonline.domain.ref.distinct.RefDistinctLocality;
import com.sgolub.commanndsonline.domain.ref.distinct.RefDistinctRegion;
import com.sgolub.commanndsonline.domain.ref.distinct.RefDistinctSupportType;
import com.sgolub.commanndsonline.domain.sec.SecUser;
import com.sgolub.commanndsonline.helpers.DateConverterHelper;
import com.sgolub.commanndsonline.helpers.JsonFlexGridDataWrapper;
import com.sgolub.commanndsonline.helpers.JsonJQGridDataWrapper;
import com.sgolub.commanndsonline.helpers.MailSender;
import com.sgolub.commanndsonline.helpers.SecurityHelper;
import com.sgolub.commanndsonline.json.ui.UIMenu;
import com.sgolub.commanndsonline.service.entity.AdvertisingRegistryService;
import com.sgolub.commanndsonline.service.entity.OperationItemService;
import com.sgolub.commanndsonline.service.entity.ProxyAdvertisingRegistryService;
import com.sgolub.commanndsonline.service.entity.UserBasketService;
import com.sgolub.commanndsonline.service.entity.UserOrderDetailService;
import com.sgolub.commanndsonline.service.entity.UserOrderService;
import com.sgolub.commanndsonline.service.ref.distinct.RefDistinctLocalityService;
import com.sgolub.commanndsonline.service.ref.distinct.RefDistinctRegionService;
import com.sgolub.commanndsonline.service.ref.distinct.RefDistinctSupportTypeService;
import com.sgolub.commanndsonline.service.sec.SecUserService;
import com.sgolub.commanndsonline.ws.entity.AdvertisingRegistryOperation;
 
@Controller 
@RequestMapping("/json")
public class JSONController {   
	
	@Autowired  
    private AdvertisingRegistryService advertisingRegistryService;
	
	@Autowired  
    private ProxyAdvertisingRegistryService proxyAdvertisingRegistryService;
	
	@Autowired  
    private OperationItemService operationItemService;
	
	@Autowired
	private RefDistinctRegionService refDistinctRegionService;
	
	@Autowired
	private RefDistinctLocalityService refDistinctLocalityService;
	
	@Autowired
	private RefDistinctSupportTypeService refDistinctSupportTypeService;
	
	@Autowired
	private UserBasketService userBasketService;
	
	@Autowired
	private UserOrderService userOrderService;
	
	@Autowired
	private UserOrderDetailService userOrderDetailService;
	
	@Autowired
	private SecUserService secUserService;

	/* -------------- MENU Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/
	
    @RequestMapping(value="/menu/{menuName}", method = RequestMethod.GET)
	public @ResponseBody UIMenu getUIMenuInJSON(@PathVariable String menuName,Principal principal) {
    	UIMenu menuItem = new UIMenu();
    	System.out.println("Requested menu.");
    	SecUser currUser = secUserService.getByName(principal.getName()); 
    	String currentUserAUTHORITY = currUser.getSecRole().getAuthority();
    	
    	if (currentUserAUTHORITY.equals("ROLE_ADMIN")) {
        	menuItem.setMenuName("Administrator Menu");
        	menuItem.setMenuItems(new String[]{"Отчёты", "Пользователи", "Заказы"});
        	menuItem.setMenuContents(new String[]{"menu", "usersList", "orderList"});
        	System.out.println("Returned ADMIN menu.");
    		
    	} else if (currentUserAUTHORITY.equals("ROLE_USER")) {
        	menuItem.setMenuName("Registered User Menu");
        	menuItem.setMenuItems(new String[]{"Регистр рекламных площадей", "Корзина", "Заказы"});
        	menuItem.setMenuContents(new String[]{"link1", "link2", "link3"});
        	System.out.println("Returned USER menu.");
    	} 
    	
		return menuItem;
 
	}     

    /* -------------- AdvertisingRegistry Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/    
    
    @RequestMapping(value="/entity/{entityName}", method = RequestMethod.GET)
	public @ResponseBody JsonFlexGridDataWrapper<AdvertisingRegistry> getAdvertisinRegistryListGET(WebRequest request) {    
    	System.out.println("GET - ARRAY SIZE IS:" + advertisingRegistryService.list().size());
    	 
    	System.out.println(request.toString());
    	 //get the current page posted from the grid.  
    	 int page = 1; //Integer.parseInt(request.getParameter("page"));  
    	 //get the list of objects to be displayed from the db calling the service  
    	 //advertisingRegistryService.list();
    	 //the total number of pages are dynamically calculated on the basis of the total number of rows in the table. get that.
    	 
    	 JsonFlexGridDataWrapper<AdvertisingRegistry> jdw = 
    			 new JsonFlexGridDataWrapper<AdvertisingRegistry>(page, 4, 
    					 advertisingRegistryService.list());  
    	 return jdw;  
    }    
    
    @RequestMapping(value="/entity/a{entityName}", method = RequestMethod.POST)
	public @ResponseBody JsonFlexGridDataWrapper<AdvertisingRegistry> getAdvertisinRegistryListPOSTFlexGrid(WebRequest request) {    
    	System.out.println("POST - ARRAY SIZE IS:" + advertisingRegistryService.list().size());
    	System.out.println("POST- Request"+ request.toString());
    	System.out.println(request.getParameterMap().toString());
    	System.out.println("rp = " 			+ request.getParameter("rp"));
    	System.out.println("sortorder = " 	+ request.getParameter("sortorder"));
    	System.out.println("page = " 		+ request.getParameter("page"));
    	System.out.println("query = " 		+ request.getParameter("query"));
    	System.out.println("sortname = " 	+ request.getParameter("sortname"));
    	System.out.println("qtype = " 		+ request.getParameter("qtype"));
    	
    	 //get the current page posted from the grid.
    	int rp 		 	= Integer.parseInt(request.getParameter("rp"));
		String sortorder 	= request.getParameter("sortorder");
		int page		 	= Integer.parseInt(request.getParameter("page"));
		String query 		= request.getParameter("query");
		String sortname 	= request.getParameter("sortname");
		String qtype 		= request.getParameter("qtype");

		
		 
		//get the list of objects to be displayed from the db calling the service  
		List<AdvertisingRegistry> result = 
				advertisingRegistryService.advansedListWithPaginationFlexGrid(rp, sortorder, page, query, sortname, qtype);
    	
		//the total number of pages are dynamically calculated on the basis of the total number of rows in the table. get that.
    	 
    	 JsonFlexGridDataWrapper<AdvertisingRegistry> jdw = 
    			 new JsonFlexGridDataWrapper<AdvertisingRegistry>(page, 
    					 advertisingRegistryService.list().size(),
    					 result);  
    	 
    	 //GoogleMailTLSHelper ss = new GoogleMailTLSHelper();
    	 //ss.Send("TESTING",request.getParameterMap().toString());
    	 return jdw;  
    }    
    
    @RequestMapping(value="/entity/b{entityName}", method = RequestMethod.POST)
	public @ResponseBody JsonJQGridDataWrapper<ProxyAdvertisingRegistry> 
    			getProxyAdvertisinRegistryListPOSTJQGrid(WebRequest request) {    
       	System.out.println("== JSONController.getProxyAdvertisinRegistryListPOSTJQGrid ==");
    	HashMap<String, String> filtersMap = new HashMap<String, String>();
    	
    	debugRequest(request);
    	
    	filtersMap.put("supportType", 	request.getParameter("filters[supportType]"));
    	filtersMap.put("regionName", 	request.getParameter("filters[regionName]"));
    	filtersMap.put("localityName", 	request.getParameter("filters[localityName]"));
    	filtersMap.put("addresString", 	request.getParameter("filters[addresString]"));
    	filtersMap.put("light", 		request.getParameter("filters[light]"));
    	filtersMap.put("priceFrom", 	request.getParameter("filters[priceFrom]"));
    	filtersMap.put("priceTo", 		request.getParameter("filters[priceTo]"));
    	filtersMap.put("priceTo", 		request.getParameter("filters[priceTo]"));
    	filtersMap.put("freeOnDate", 	request.getParameter("filters[freeOnDate]"));
    	
    	
    			 
    	int rowsPerPage 		 	= Integer.parseInt(request.getParameter("rows"));
    	int currentPage				= Integer.parseInt(request.getParameter("page"));
    	String sortByColumn			= request.getParameter("sidx");
    	String sortMode				= request.getParameter("sord");

    	List<ProxyAdvertisingRegistry> result = proxyAdvertisingRegistryService.advansedListWithPaginationJQGrid
		(rowsPerPage, currentPage, sortByColumn, sortMode, filtersMap);
    	
    	System.out.println("result.size() :" + 	result.size());
    	System.out.println("rowsPerPage :" + 	rowsPerPage);
    	int totalPages = result.size()/rowsPerPage + (result.size()%rowsPerPage>0?1:0);
    	
    	System.out.println("totalPages :" + totalPages);
    	
    	if (currentPage > totalPages) currentPage = 1;
    	int vFromIndex = rowsPerPage * (currentPage-1);
    	int vToIndex = (rowsPerPage * currentPage >result.size())?(result.size()):(rowsPerPage * currentPage);
    	
    	JsonJQGridDataWrapper<ProxyAdvertisingRegistry> jdw = 
    			new JsonJQGridDataWrapper<ProxyAdvertisingRegistry>(
    					totalPages,
    					currentPage,
    					result.size(),
    					result.subList(vFromIndex, vToIndex )); 
    	
    	System.out.println("RESULT SIZE IS :" + result.size());
    	 return jdw;
    }  
    
    /* -------------- UserBasket Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/  
    
    @RequestMapping(value="/entity/userBasket", method = RequestMethod.GET)
	public @ResponseBody JsonJQGridDataWrapper<UserBasket> getUserBasketListGET(WebRequest request,Principal principal) {
    	System.out.println("===== getUserBasketListGET =====");
    	if (principal == null) {
    		return null;
    	}
       	System.out.println("Current User  = :" + principal.getName());
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);

       	int rowsPerPage 		 	= Integer.parseInt(request.getParameter("rows"));
    	int currentPage				= Integer.parseInt(request.getParameter("page"));
    	String sortByColumn			= request.getParameter("sidx");
    	String sortMode				= request.getParameter("sord");
    	
    	List<UserBasket> result = userBasketService.
    			advansedListCurrentWithPaginationJQGrid(currUserId, rowsPerPage, currentPage, sortByColumn, sortMode);
 
    	System.out.println("result.size() :" + 	result.size());
    	System.out.println("rowsPerPage :" + 	rowsPerPage);
    	int totalPages = result.size()/rowsPerPage + (result.size()%rowsPerPage>0?1:0);
    	
    	System.out.println("totalPages :" + totalPages);
    	
    	if (currentPage > totalPages) currentPage = 1;
    	int vFromIndex = rowsPerPage * (currentPage-1);
    	int vToIndex = (rowsPerPage * currentPage >result.size())?(result.size()):(rowsPerPage * currentPage);
     	
     	JsonJQGridDataWrapper<UserBasket> jdw = 
    			new JsonJQGridDataWrapper<UserBasket>(
    					totalPages,
    					currentPage,
    					result.size(),
    					result.subList(vFromIndex, vToIndex )); 
    	
    	return jdw; 
  }   
    
    
    @RequestMapping(value="/entity/userBasket", method = RequestMethod.POST)
	public @ResponseBody JsonJQGridDataWrapper<UserBasket> getUserBasketListPOST(WebRequest request,Principal principal) {
    	System.out.println("===== getUserBasketListPOST =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("Current User  = :" + principal.getName());
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);

       	int rowsPerPage 		 	= Integer.parseInt(request.getParameter("rows"));
    	int currentPage				= Integer.parseInt(request.getParameter("page"));
    	String sortByColumn			= request.getParameter("sidx");
    	String sortMode				= request.getParameter("sord");
    	
    	List<UserBasket> result = userBasketService.
    			advansedListCurrentWithPaginationJQGrid(currUserId, rowsPerPage, currentPage, sortByColumn, sortMode);
 
    	System.out.println("result.size() :" + 	result.size());
    	System.out.println("rowsPerPage :" + 	rowsPerPage);
    	int totalPages = result.size()/rowsPerPage + (result.size()%rowsPerPage>0?1:0);
    	
    	System.out.println("totalPages :" + totalPages);
    	
    	if (currentPage > totalPages) currentPage = 1;
    	int vFromIndex = rowsPerPage * (currentPage-1);
    	int vToIndex = (rowsPerPage * currentPage >result.size())?(result.size()):(rowsPerPage * currentPage);
     	
     	JsonJQGridDataWrapper<UserBasket> jdw = 
    			new JsonJQGridDataWrapper<UserBasket>(
    					totalPages,
    					currentPage,
    					result.size(),
    					result.subList(vFromIndex, vToIndex )); 
    	
    	return jdw;  
  }  
    
    
    @RequestMapping(value="/entity/userBasket/deleteAll", method = RequestMethod.POST)
	public @ResponseBody String clearCurrentUserBasketPOST(WebRequest request,Principal principal) {
    	System.out.println("===== clearCurrentUserBasketPOST =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("Current User  = :" + principal.getName());
    	
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);
    	
    	String  result = userBasketService.clearCurrentUserBasket(currUserId);
    	
    	System.out.println("RESPONSE IS:" + result);
    	
    	return "{\"basketCleared for UserId \":" + currUserId + ", \"result\":\"" + result + "\"}";  
  }  
    
    @RequestMapping(value="/entity/userBasket/checkItem", method = RequestMethod.POST)
	public @ResponseBody String checkOneItemPOST(@RequestParam("itemBasketId") Integer itemBasketId,
															WebRequest request,Principal principal) {
    	System.out.println("===== checkOneItemPOST =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("userBasketService itemBasketId:" + itemBasketId);
    	String result = userBasketService.checkOneItem(itemBasketId);
    	
    	return "{\"itemChecked\":" + itemBasketId + ", \"result\":\"" + result + "\"}";
  } 

    
    @RequestMapping(value="/entity/userBasket/add", method = RequestMethod.GET)
 	public @ResponseBody String addItemToBasket(@RequestParam("itemId") Integer itemId,
 												@RequestParam("firstFreeDate") String firstFreeDate,
 												WebRequest request,Principal principal) {
     	System.out.println("===== addItemToBasket ===== itemId = " + itemId);
     	System.out.println("===== addItemToBasket ===== firstFreeDate = " + firstFreeDate);
     	
     	Date frstFreeDate = new Date();
     	
     	if (principal == null) {
     		return null;
     	}
     	
     	Integer currUserId = secUserService.getByName(principal.getName()).getId();
     	if (firstFreeDate.length() > 0){
     		frstFreeDate = DateConverterHelper.convertToDate(firstFreeDate);
     	} 
     	
     	
     	String result = userBasketService.addItemToCurrentUserBasket(currUserId, itemId, frstFreeDate);
     	
     	
     	return "{\"itemAdded\":" + itemId + ", \"result\":\"" + result + "\"}";
    }

    @RequestMapping(value="/entity/userBasket/del={itemId}", method = RequestMethod.GET)
 	public @ResponseBody String removeItemToBasket(@PathVariable Integer itemId, WebRequest request,Principal principal) {
    	System.out.println("===== removeItemToBasket ===== itemId = " + itemId);
     	if (principal == null) {
     		return null;
     	}
     	
     	userBasketService.remove(itemId);
     	return "OK";
    }
    
    
    
	@RequestMapping(value="/entity/userBasket/edit", method = RequestMethod.POST)
  	public @ResponseBody String editItemToBasket(@RequestParam("id") Integer id,
  												 @RequestParam("oper") String oper,
  												 WebRequest request,Principal principal) {
    	
     	System.out.println("===== removeItemToBasket ===== ID = " + id);
     	System.out.println("===== removeItemToBasket ===== OPERATION = " + oper);

      	if (principal == null) {
      		return null;
      	}
     	
     	if (oper.equals("del")) {
     		System.out.println("-EXECUTE DELETE-");
     		userBasketService.remove(id);
     	}
     	
     	if (oper.equals("edit")) {
     		System.out.println("-EXECUTE UPDATE-");
        	String strBeginCommandDate = 	request.getParameter("beginCommandDate");
        	String strEndCommandDate = 		request.getParameter("endCommandDate");
        	System.out.println("strBeginCommandDate=" + strBeginCommandDate);
        	System.out.println("strEndCommandDate=" + strEndCommandDate);
        	
        	Date bd = DateConverterHelper.convertToDate(strBeginCommandDate);
        	Date ed = DateConverterHelper.convertToDate(strEndCommandDate);
        	
        	UserBasket item = userBasketService.get(id);
        	
        	if (item != null) {
        		item.setBeginCommandDate(bd);
        		item.setEndCommandDate(ed);
        	}
        	
        	userBasketService.update(item);

     	} 
      	

      	return "OK";
     } 
    
	@RequestMapping(value="/entity/userBasket/submit", method = RequestMethod.GET)
  	public @ResponseBody String editItemToBasket( WebRequest request,Principal principal) {
      	if (principal == null) {
      		return null;
      	}
      	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
      	
		String result = userBasketService.submitCurrentUserBasket(currUserId);
		
		
		return "{\"result\":\"Order placed - Order Nr."+ result +"\"}";
	}
    
    
	@RequestMapping(value="/entity/userBasket/listTotal", method = RequestMethod.GET)
	public @ResponseBody JsonJQGridDataWrapper<ProxyUserBasketTotal> userBasketListTotalGET( WebRequest request,Principal principal) {
    	System.out.println("===== userBasketListTotalGET =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("Current User  = :" + principal.getName());
    	
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);
    	
    	List<ProxyUserBasketTotal> userBasketTOTAL = userBasketService.listByUserId(currUserId);
    	
    	System.out.println("GET - ARRAY SIZE IS:" + userBasketService.listCurrentUserBasket(currUserId).size());
    	System.out.println("userBasketService term:" + request.getParameter("term"));
    	
     	JsonJQGridDataWrapper<ProxyUserBasketTotal> jdw = 
    			new JsonJQGridDataWrapper<ProxyUserBasketTotal>(
    					1,
    					100,
    					userBasketTOTAL.size(),
    					userBasketTOTAL); 
    	
    	return jdw;  
	}		
	
	@RequestMapping(value="/entity/userBasket/listTotal", method = RequestMethod.POST)
	public @ResponseBody JsonJQGridDataWrapper<ProxyUserBasketTotal> userBasketListTotalPOST( WebRequest request,Principal principal) {
    	System.out.println("===== userBasketListTotalGET =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("Current User  = :" + principal.getName());
    	
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);
    	
    	List<ProxyUserBasketTotal> userBasketTOTAL = userBasketService.listByUserId(currUserId);
    	
    	System.out.println("GET - ARRAY SIZE IS:" + userBasketTOTAL.size());
    	
     	JsonJQGridDataWrapper<ProxyUserBasketTotal> jdw = 
    			new JsonJQGridDataWrapper<ProxyUserBasketTotal>(
    					1,
    					100,
    					userBasketTOTAL.size(),
    					userBasketTOTAL); 
    	
    	return jdw;  
	}	
	
	
	
	
	
	
	@RequestMapping(value="/entity/userBasket/listSumTotal", method = RequestMethod.GET)
	public @ResponseBody Integer userBasketListTotalSumPOST( WebRequest request,Principal principal) {
    	System.out.println("===== userBasketListTotalSumPOST =====");
    	if (principal == null) {
    		return null;
    	}
    	System.out.println("Current User  = :" + principal.getName());
    	
    	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
    	System.out.println("currUserId = :" + currUserId);
    	
    	Integer basketSum = userBasketService.totalSumByUserId(currUserId);
     	
    	return basketSum;  
	}	
		
	
    /* -------------- UserOrder Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/    
    
    
    
    @RequestMapping(value="/entity/userOrder", method = RequestMethod.GET)
 	public @ResponseBody JsonJQGridDataWrapper<UserOrder> getUserOrderListGET(WebRequest request,Principal principal) {
     	System.out.println("===== getUserOrderListGET =====");
     	if (principal == null) {
     		return null;
     	}
     	System.out.println("Current User  = :" + principal.getName());
     	
     	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
     	System.out.println("currUserId = :" + currUserId);	
     	
     	List<UserOrder> userOrderLST = userOrderService.listCurrentUserOrder(currUserId);
     	
     	System.out.println("GET - ARRAY SIZE IS:" + userOrderLST.size());
     	System.out.println("userOrderService term:" + request.getParameter("term"));
     	
     	JsonJQGridDataWrapper<UserOrder> jdw = 
    			new JsonJQGridDataWrapper<UserOrder>(
    					1,
    					100,
    					userOrderLST.size(),
    					userOrderLST); 
    	return jdw;  
   }   
  
    
    @RequestMapping(value="/entity/userOrder/admin", method = RequestMethod.GET)
 	public @ResponseBody JsonJQGridDataWrapper<UserOrder> getUserOrderListGETadmin(WebRequest request,Principal principal) {
     	System.out.println("===== getUserOrderListGETadmin =====");
     	if (principal == null) {
     		return null;
     	}
     	System.out.println("Current User  = :" + principal.getName());
     	
     	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
     	System.out.println("currUserId = :" + currUserId);
     	
     	List<UserOrder> userOrderLST;
     	if (currUserId == 1) { //User is Main manager
     		userOrderLST = userOrderService.list();	
     	} else { //User is Simple manager
     		userOrderLST = userOrderService.list();
     	}
     	
     	System.out.println("GET - ARRAY SIZE IS:" + userOrderLST.size());
     	System.out.println("userOrderService term:" + request.getParameter("term"));
     	
     	JsonJQGridDataWrapper<UserOrder> jdw = 
    			new JsonJQGridDataWrapper<UserOrder>(
    					1,
    					100,
    					userOrderLST.size(),
    					userOrderLST); 
    	return jdw;  
   }  
    
    
    @RequestMapping(value="/entity/userOrder/admin", method = RequestMethod.POST)
 	public @ResponseBody JsonJQGridDataWrapper<UserOrder> getUserOrderListPOSTadmin(WebRequest request,Principal principal) {
     	System.out.println("===== getUserOrderListGETadmin =====");
     	if (principal == null) {
     		return null;
     	}
     	System.out.println("Current User  = :" + principal.getName());
     	
     	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
     	System.out.println("currUserId = :" + currUserId);
     	
     	HashMap<String, String> filtersMap = new HashMap<String, String>();
    	
     	
     	if (currUserId == 1 || currUserId == 777  ) { //User is Main manager
     		filtersMap.put("currUser", 		"");
     	} else { //User is Simple manager
     		filtersMap.put("currUser", 		currUserId.toString());
     	}
     	
    	filtersMap.put("company", 		request.getParameter("filters[company]"));
    	filtersMap.put("orderStatus", 	request.getParameter("filters[state]"));
    	filtersMap.put("dateFrom", 		request.getParameter("filters[dateFrom]"));
    	filtersMap.put("dateTo", 		request.getParameter("filters[dateTo]"));
    			 
    	int rowsPerPage 		 	= Integer.parseInt(request.getParameter("rows"));
    	int currentPage				= Integer.parseInt(request.getParameter("page"));
    	String sortByColumn			= request.getParameter("sidx");
    	String sortMode				= request.getParameter("sord");     	
     	
     	
     	List<UserOrder> userOrderLST = userOrderService.filter(sortByColumn,sortMode, filtersMap);

    	System.out.println("result.size() :" + 	userOrderLST.size());
    	System.out.println("rowsPerPage :" + 	rowsPerPage);
    	int totalPages = userOrderLST.size()/rowsPerPage + (userOrderLST.size()%rowsPerPage>0?1:0);
    	
    	System.out.println("totalPages :" + totalPages);
    	
    	if (currentPage > totalPages) currentPage = 1;
    	int vFromIndex = rowsPerPage * (currentPage-1);
    	int vToIndex = (rowsPerPage * currentPage >userOrderLST.size())?(userOrderLST.size()):(rowsPerPage * currentPage);
    	
    	JsonJQGridDataWrapper<UserOrder> jdw = 
    			new JsonJQGridDataWrapper<UserOrder>(
    					totalPages,
    					currentPage,
    					userOrderLST.size(),
    					userOrderLST.subList(vFromIndex, vToIndex )); 
     	
     	

     	
     	
     	System.out.println("GET - ARRAY SIZE IS:" + userOrderLST.size());
    	return jdw;  
   }      
    
    @RequestMapping(value="/entity/userOrder", method = RequestMethod.POST)
  	public @ResponseBody JsonJQGridDataWrapper<UserOrder> getUserOrderListPOST(WebRequest request,Principal principal) {
      	System.out.println("===== getUserOrderListPOST =====");
      	if (principal == null) {
      		return null;
      	}
      	System.out.println("Current User  = :" + principal.getName());
      	
      	Integer currUserId = secUserService.getByName(principal.getName()).getId(); 
      	System.out.println("currUserId = :" + currUserId);	
      	
      	List<UserOrder> userOrderLST = userOrderService.listCurrentUserOrder(currUserId);
      	
      	System.out.println("GET - ARRAY SIZE IS:" + userOrderService.listCurrentUserOrder(currUserId).size());
      	System.out.println("userOrderService term:" + request.getParameter("term"));
      	
      	JsonJQGridDataWrapper<UserOrder> jdw = 
     			new JsonJQGridDataWrapper<UserOrder>(
     					1,
     					100,
     					userOrderLST.size(),
     					userOrderLST); 
     	return jdw;  
    }   
    
    
	@RequestMapping(value="/entity/userOrder/edit", method = RequestMethod.POST)
  	public @ResponseBody String editOrder(@RequestParam("id") Integer id,
  												 @RequestParam("oper") String oper,
  												 WebRequest request,Principal principal) {
    	
     	System.out.println("===== editOrder ===== ID = " + id);
     	System.out.println("===== editOrder ===== OPERATION = " + oper);
     	String result = "";
      	if (principal == null) {
      		return null;
      	}
     	
     	if (oper.equals("del")) {
     		System.out.println("-EXECUTE DELETE-");
     		userOrderService.remove(id); //Added by VLAD Request
//     		if (userOrderService.get(id).getOrderStatus() == 0){ //Delete Only Projects
//     			userOrderService.remove(id);	
//     		} else {
//     			return "";
//     		}
     		
     	}
      	return "{\"result\":\"Order deleted. "+ result +"\"}";
     } 
	
	@RequestMapping(value="/entity/userOrder/submit", method = RequestMethod.POST)
  	public @ResponseBody String submitOrder(@RequestParam("id") Integer id,
  											WebRequest request,Principal principal) {
     	System.out.println("===== submitOrder ===== ID = " + id);
     	String result = "";
      	if (principal == null) {
      		return null;
      	} 
      	UserOrder item = userOrderService.get(id);
      	item.setOrderStatus(1);
      	userOrderService.update(item);
      	MailSender.submitOrder(item, 
      						secUserService.getByName(principal.getName()),
      						userOrderDetailService.listDetailByOrderId(id));
      	return "{\"result\":\"Order submitted. "+ result +"\"}";
     } 	
	
	
	@RequestMapping(value="/entity/userOrder/approve", method = RequestMethod.POST)
  	public @ResponseBody String approveOrder(@RequestParam("id") Integer id,
  											WebRequest request,Principal principal) {
     	System.out.println("===== approveOrder ===== ID = " + id);
     	String result = "";
      	if (principal == null) {
      		return null;
      	} 
      	UserOrder item = userOrderService.get(id);
      	item.setOrderStatus(2);
      	userOrderService.update(item);
      	MailSender.approveOrder(item, 
      						secUserService.getByName(principal.getName()),
      						userOrderDetailService.listDetailByOrderId(id));
      	return "{\"result\":\"Order submitted. "+ result +"\"}";
     } 		
	
	
	@RequestMapping(value="/entity/userOrder/reject", method = RequestMethod.POST)
  	public @ResponseBody String rejectOrder(@RequestParam("id") Integer id,
  											WebRequest request,Principal principal) {
     	System.out.println("===== rejectOrder ===== ID = " + id);
     	String result = "";
      	if (principal == null) {
      		return null;
      	} 
      	UserOrder item = userOrderService.get(id);
      	item.setOrderStatus(3);
      	userOrderService.update(item);
      	MailSender.rejectOrder(item, 
      						secUserService.getByName(principal.getName()),
      						userOrderDetailService.listDetailByOrderId(id));
      	return "{\"result\":\"Order submitted. "+ result +"\"}";
     } 		
	
 
    @RequestMapping(value="/entity/userOrderDetail", method = RequestMethod.GET)
  	public @ResponseBody JsonJQGridDataWrapper<UserOrderDetail> getUserOrderDetailListGET(
  							@RequestParam("orderId") Integer orderId, 
    						WebRequest request,Principal principal) {
      	System.out.println("===== getUserOrderDetailListGET =====");
      	
      	List<UserOrderDetail> userOrderDetailLST = 
      			userOrderDetailService.listDetailByOrderId(orderId);
      	
      	System.out.println("GET - ARRAY SIZE IS:" + userOrderDetailLST.size());
      	System.out.println("userOrderDetailService orderId:" + orderId);
      	
      	JsonJQGridDataWrapper<UserOrderDetail> jdw = 
     			new JsonJQGridDataWrapper<UserOrderDetail>(
     					1,
     					100,
     					userOrderDetailLST.size(),
     					userOrderDetailLST); 
     	return jdw;  
    }       

    /* -------------- USER MANAGEMENT Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/    
    @RequestMapping(value="/entity/userManagement/list", method = RequestMethod.GET)
  	public @ResponseBody JsonJQGridDataWrapper<SecUser> getUsersList(WebRequest request,Principal principal) {
      	System.out.println("===== getUsersListGET =====");
      	System.out.println("===== USER NAME =====" + principal.getName());
      	
      	List<SecUser> usersList =
      			secUserService.list();
      	
      	System.out.println("GET - ARRAY SIZE IS:" + usersList.size());
      	
      	JsonJQGridDataWrapper<SecUser> jdw = 
     			new JsonJQGridDataWrapper<SecUser>(
     					1,
     					100,
     					usersList.size(),
     					usersList); 
      	
      	System.out.println("GET - JSON SIZE IS:" + jdw.getTotal());
     	return jdw;  
    } 
 
    @RequestMapping(value="/entity/userManagement/listManagers", method = RequestMethod.GET)
  	public @ResponseBody String getManagersList(WebRequest request,Principal principal) {
      	System.out.println("===== getManagersListGET =====");
      	if (principal == null) {
      		return null;
      	}
      	System.out.println("===== USER NAME =====" + principal.getName());
      	String result = "<select>";
      	
      	List<SecUser> managersList =
      			secUserService.listManagers();
      	
      	System.out.println("GET - ARRAY SIZE IS:" + managersList.size());
      	
      	Iterator<SecUser> itr = managersList.iterator();
      	while(itr.hasNext()) {
      		SecUser element = itr.next();
	    	 result += "<option value='" + element.getId() + "'>" + element.getName() + "</option>";
      	} 
	    
      	result += "</select>";
      	
     	return result;  
    } 
    
    
    
	@RequestMapping(value="/entity/userManagement/edit", method = RequestMethod.POST)
  	public @ResponseBody String editUser(@RequestParam("id") Integer id, 
  										// @RequestParam("manager.id") Integer managerId,
  										@RequestParam(value="manager.id", required=false) Integer managerId,
  										 @RequestParam("oper") String oper,
  										 WebRequest request,Principal principal) {
    	
     	System.out.println("===== editUser ===== ID = " + id);
     	System.out.println("===== editUser ===== MANAGER ID = " + managerId);
     	System.out.println("===== editUser ===== OPERATION = " + oper);

      	if (principal == null) {
      		return null;
      	}
     	
     	if (oper.equals("del")) {
     		if (id != null) {
     			System.out.println("-EXECUTE DELETE-");
         		secUserService.remove(id);
     		} else {
     			System.out.println("-CAN'T EXECUTE DELETE - NULL PARAMETERS-");
     		}
     		
     	}
     	
     	if (oper.equals("edit")) {
     		
     		if (id != null && managerId != null){
     			System.out.println("-EXECUTE UPDATE-");
     			SecUser editedUser = secUserService.get(id);
     			SecUser newManager = secUserService.get(managerId);
     			editedUser.setManager(newManager);
     			editedUser.setEnabled(1);
     			secUserService.update(editedUser);
     	    	MailSender.newUserRegisterationApproved(editedUser);

     			
     		} else {
     			System.out.println("-CAN'T EXECUTE UPDATE - NULL PARAMETERS-");
     		}

     	} 
      	

      	return "OK";
     } 
    
    
    
    
    
    @RequestMapping(value="/entity/test", method = RequestMethod.GET)
  	public @ResponseBody List<OperationItem> test(WebRequest request,Principal principal) {
      	System.out.println("===== TEST =====");
      	
      	return operationItemService.listByAdvertisingRegistryId(1146);  
    }      
    
    /* -------------- DISTINCT Routines -------------------------------- 
     * 
     * 
     * 
     * ------------------------------------------------------------------*/    
     
    @RequestMapping(value="/distinct/region{distinctName}", method = RequestMethod.GET)
	public @ResponseBody List<RefDistinctRegion> getRefDistinctRegionList(WebRequest request) {    
    	//System.out.println("GET - ARRAY SIZE IS:" + refDistinctRegionService.list().size());
    	System.out.println("getRefDistinctRegionList term:" + request.getParameter("term"));
    	  
    	return refDistinctRegionService.match(request.getParameter("term"));  
    }
     
    @RequestMapping(value="/distinct/locality{distinctName}", method = RequestMethod.GET)
	public @ResponseBody List<RefDistinctLocality> getRefDistinctLocalityList(WebRequest request) {    
    	//System.out.println("GET - ARRAY SIZE IS:" + refDistinctRegionService.list().size());
    	System.out.println("getRefDistinctLocalityList term:" + request.getParameter("term"));
    	   
    	 return refDistinctLocalityService.match(request.getParameter("term"));  
    }      
    
    
    @RequestMapping(value="/distinct/supportType{distinctName}", method = RequestMethod.GET)
	public @ResponseBody List<RefDistinctSupportType> getRefDistinctSupportTypeList(WebRequest request) {    
    	//System.out.println("GET - ARRAY SIZE IS:" + refDistinctRegionService.list().size());
    	System.out.println("getRefDistinctSupportTypeList term:" + request.getParameter("term"));
    	   
    	 //return refDistinctSupportTypeService.match(request.getParameter("term"));  
    	return refDistinctSupportTypeService.match(request.getParameter("term"));  
    }    
    
    
    private void debugRequest(WebRequest request){
       	System.out.println(request.getParameterMap().toString());
    	System.out.println("sord :" + request.getParameter("sord"));
    	System.out.println("page :" + request.getParameter("page")); 
    	System.out.println("nd :" 	+ request.getParameter("nd")); 
    	System.out.println("sidx :" + request.getParameter("sidx")); 
    	System.out.println("_search :" + request.getParameter("_search")); 
    	System.out.println("rows :" + request.getParameter("rows"));
    	System.out.println("filters :" + request.getParameter("filters"));
    	System.out.println("filters[supportType] :" + request.getParameter("filters[supportType]"));
    	System.out.println("filters[regionName] :" + 	request.getParameter("filters[regionName]"));
    	System.out.println("filters[localityName] :" + 	request.getParameter("filters[localityName]"));
    	System.out.println("filters[addresString] :" + 	request.getParameter("filters[addresString]"));
    	System.out.println("filters[light] :" + 		request.getParameter("filters[light]"));
    	System.out.println("filters[priceFrom] :" + 	request.getParameter("filters[priceFrom]"));
    	System.out.println("filters[priceTo] :" + 		request.getParameter("filters[priceTo]"));	
    }
    
    
//    @RequestMapping(value="/distinct/region{distinctName}", method = RequestMethod.GET)
//	public @ResponseBody List<ReferenceItem> getRefDistinctRegionList(WebRequest request) {    
//    	System.out.println("GET - ARRAY SIZE IS:" + refDistinctRegionService.list().size());
//    	
//    	System.out.println("getRefDistinctRegionList term:" + request.getParameter("term"));
//    	
//    	List<ReferenceItem> resultList = new ArrayList<ReferenceItem>();
//    	Iterator<RefDistinctRegion> it=refDistinctRegionService.list().iterator();
//
//        while(it.hasNext()) {
//        	RefDistinctRegion item = it.next();
//        	resultList.add(new ReferenceItem(item.getRegionName(), item.getRegionCod()));
//        }
//     return resultList;  
//    }    
    
}



//@RequestMapping(value="/entity/userManagement/listManagers", method = RequestMethod.GET)
//	public @ResponseBody JsonJQGridDataWrapper<SecUser> getManagersList(WebRequest request,Principal principal) {
//  	System.out.println("===== getManagersListGET =====");
//  	if (principal == null) {
//  		return null;
//  	}
//  	System.out.println("===== USER NAME =====" + principal.getName());
//  	
//  	List<SecUser> managersList =
//  			secUserService.listManagers();
//  	
//  	System.out.println("GET - ARRAY SIZE IS:" + managersList.size());
//  	
//  	JsonJQGridDataWrapper<SecUser> jdw = 
// 			new JsonJQGridDataWrapper<SecUser>(
// 					1,
// 					100,
// 					managersList.size(),
// 					managersList); 
//  	
//  	System.out.println("GET - JSON SIZE IS:" + jdw.getTotal());
// 	return jdw;  
//} 